package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class EchoCloent03 {
    private DatagramSocket socket;
    private String severIp;
    private int severPort;

    public EchoCloent03(String severIp, int severPort) throws Exception{
        this.severIp=severIp;
        this.severPort=severPort;
        socket=new DatagramSocket();
    }

    //读取请求 
    //发送请求
    //读取响应
    //显示响应

    public void start() throws Exception  {
        System.out.println("客户端启动");
        Scanner scanner=new Scanner(System.in);
        while(true){
            //读取用户输入内容
            System.out.println(">");
            String request=scanner.next();
  
            //构造udp请求 并发送
            DatagramPacket reqPacket=new DatagramPacket(request.getBytes(),
            request.getBytes().length,InetAddress.getByName(severIp),severPort);
            socket.send(reqPacket);
            //读取响应
            DatagramPacket respPacket=new DatagramPacket(new byte[4096],4096 );
            socket.receive(respPacket);
            //将响应内容解析成字符串
            String response=new String(respPacket.getData(),0,respPacket.getLength());
            //显示响应内容
            System.out.println(response);
        }
    }



    public static void main(String[] args) throws Exception  {
        EchoCloent03 echoCloent03=new EchoCloent03("127.0.0.1", 9070);
        echoCloent03.start();
    }
}
